import 'package:flutter/material.dart';
import 'package:wanandroid_flutter/api/common_service.dart';

import 'package:wanandroid_flutter/utils/router_push_util.dart';
import 'package:wanandroid_flutter/utils/timeline_util.dart';
import 'package:wanandroid_flutter/model/system_tree_model.dart';
import 'package:wanandroid_flutter/model/system_tree_content_model.dart';
import 'package:wanandroid_flutter/components/public_widget.dart';

class SystemTreeContentPage extends StatefulWidget {
  final SystemTreeData data;

  SystemTreeContentPage({Key key, @required this.data}) : super(key: key);

  _SystemTreeContentPageState createState() => _SystemTreeContentPageState();
}

class _SystemTreeContentPageState extends State<SystemTreeContentPage>
    with TickerProviderStateMixin {
  SystemTreeData _datas;
  TabController _tabController;

  void initState() {
    super.initState();
    _datas = widget.data;
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    _tabController = TabController(vsync: this, length: _datas.children.length);
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).accentColor,
        title: Text(_datas.name),
        bottom: TabBar(
          controller: _tabController,
          tabs: _datas.children
              .map((SystemTreeChild child) => Tab(
                    text: child.name,
                  ))
              .toList(),
          indicatorColor: Colors.white10,
          isScrollable: true,
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: _datas.children
            .map((SystemTreeChild child) => NewsList(id: child.id))
            .toList(),
      ),
    );
  }
}

class NewsList extends StatefulWidget {
  final int id;
  NewsList({Key key, @required this.id}) : super(key: key);

  _NewsListState createState() => _NewsListState();
}

class _NewsListState extends State<NewsList> {
  List<SystemTreeContentChild> _datas = List();
  ScrollController _scrollController = ScrollController();
  int _page = 1;

  bool isAllData = false;
  bool noResult = false;

  void initState() {
    super.initState();
    _getData();

    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _getMore();
      }
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: RefreshIndicator(
        onRefresh: _getData,
        child: ListView.separated(
          padding: const EdgeInsets.all(16.0),
          itemBuilder: _renderRow,
          itemCount: _datas.length > 0 ? _datas.length + 1 : 1,
          controller: _scrollController,
          separatorBuilder: (context, int index) {
            return Container(
              height: 0.5,
              color: Colors.grey[600],
            );
          },
        ),
      ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    if (noResult) return NoResultWidget();

    if (index < _datas.length) {
      return _itemView(context, index);
    }
    if (isAllData) return NoMoreWidget();
    return GetMoreWidget();
  }

  Widget _itemView(BuildContext context, int index) {
    return InkWell(
      child: _newsRow(_datas[index]),
      onTap: () {
        RouterPush.toWebview(context, _datas[index].title, _datas[index].link);
      },
    );
  }

  Widget _newsRow(SystemTreeContentChild child) {
    return Column(
      children: <Widget>[
        Container(
          padding: EdgeInsets.fromLTRB(8, 16, 8, 0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text(
                child.author,
                style: TextStyle(
                  fontSize: 12.0,
                  color: Colors.grey[800],
                ),
              ),
              Expanded(
                child: Text(
                  TimelineUtil.format(child.publishTime),
                  style: TextStyle(fontSize: 12.0, color: Colors.grey[800]),
                  textAlign: TextAlign.right,
                ),
              ),
            ],
          ),
        ),
        Container(
          padding: const EdgeInsets.fromLTRB(8, 12, 8, 12),
          child: Row(
            children: <Widget>[
              Expanded(
                child: Text(
                  child.title,
                  style: TextStyle(
                      fontSize: 16.0,
                      color: Colors.black,
                      fontWeight: FontWeight.bold),
                  textAlign: TextAlign.left,
                ),
              )
            ],
          ),
        ),
        Container(
          padding: const EdgeInsets.fromLTRB(8, 0, 8, 16),
          child: Row(
            children: <Widget>[
              Text(
                child.superChapterName,
                style: TextStyle(fontSize: 12.0, color: Colors.grey),
              ),
              Text(
                "/" + child.chapterName,
                style: TextStyle(fontSize: 12.0, color: Colors.grey),
                textAlign: TextAlign.right,
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// ==============================
  Future<Null> _getData() async {
    _page = 0;
    int _id = widget.id;

    CommonService().getSystemTreeContent(
        (SystemTreeContentModel systemTreeContentModel) {
      setState(() {
        if (systemTreeContentModel.data.datas.length == 0) {
          noResult = true;
        } else if (systemTreeContentModel.data.datas.length != 20) {
          isAllData = true;
        }
        _datas = systemTreeContentModel.data.datas;
      });
    }, _page, _id);
  }

  Future<Null> _getMore() async {
    _page++;
    int _id = widget.id;

    CommonService().getSystemTreeContent(
        (SystemTreeContentModel systemTreeContentModel) {
      setState(() {
        if (systemTreeContentModel.data.datas.length != 20) {
          isAllData = true;
        }
        _datas.addAll(systemTreeContentModel.data.datas);
      });
    }, _page, _id);
  }
}
